/**
 * @Author: easten
 * @Created: 2024-08-04 15:21:31
 * @Description: 报警提示
 *
 */
import { Alarm } from "@icon-park/react";
import { ApiPoint } from "_common/api/iot";
import { IotDeviceData, ModuleCommonProps } from "_common/DataType";
import { IotPoint } from "_common/entity";
import { iotDataService } from "_common/service";
import classNames from "classnames";
import { AlarmSounding } from "components";
import dayjs from "dayjs";
import React, { useEffect, useState } from "react";
import { Button, Dialog, List, Space, Switch, Tooltip } from "tdesign-react";
type AlarmTipProps = ModuleCommonProps & {};
const AlarmTip: React.FC<AlarmTipProps> = (props: AlarmTipProps) => {
  const { className, axios } = props;
  const [isAlarm, setIsAlarm] = useState(false);
  const [isAlarmSounding, setIsAlarmSounding] = useState(true);
  const [points, setPoints] = useState<IotPoint[]>([]);
  const [alarmList, setAlarmList] = useState<IotDeviceData[]>([]);

  const { ListItem, ListItemMeta } = List;
  // 对话框状态
  const [visible, setVisible] = useState<boolean>(false);

  // 查询实时数据列表
  const apiPoint = new ApiPoint(axios);

  useEffect(() => {
    // 获取点位数据
    getPoints();
    let inter = setInterval(() => {
      getPoints();
    }, 1000 * 60);
    return () => {
      clearInterval(inter);
    };
  }, []);

  const getPoints = () => {
    apiPoint.getAll().then((response) => {
      if (response && response.code == 200 && response.data) {
        console.log("response.data:", response.data);
        setPoints(response.data);
      }
    });
  };

  useEffect(() => {
    console.log("alarmList:", alarmList);
  }, [alarmList]);

  useEffect(() => {
    // 订阅实时数据
    let sub = iotDataService.iot.subscribe((data) => {
      if (data.dtCode == 116) {
        // 检查status是否为1或2，决定是否添加或更新
        setAlarmList((prevAlarmList) => {
          const existingIndex = prevAlarmList.findIndex(
            (item) => item.deviceCode === data.deviceCode
          );

          if (data.status === 1 || data.status === 2) {
            if (existingIndex !== -1) {
              // 如果 deviceCode 已经存在，更新该项
              return prevAlarmList.map((item, index) =>
                index === existingIndex ? data : item
              );
            } else {
              // 如果 deviceCode 不存在，新增该项
              return [...prevAlarmList, data];
            }
          } else {
            if (existingIndex !== -1) {
              // 如果 deviceCode 已经存在，且 status 不是 1 或 2，移除该项
              return prevAlarmList.filter(
                (item) => item.deviceCode !== data.deviceCode
              );
            }
            // 如果 deviceCode 不存在且 status 不是 1 或 2，保持不变
            return prevAlarmList;
          }
        });
      }
    });
    return () => {
      sub.unsubscribe();
    };
  }, []);

  useEffect(() => {
    // getRealtime();
  }, [isAlarmSounding]);

  /* const getRealtime = async () => {
    const response = await apiRealtime.getAll();
    if (response && response.code == 200 && response.data) {
      setDataList(
        response.data?.filter((item) => item.status == 1 || item.status == 2)
      );
    }
  }; */

  useEffect(() => {
    setIsAlarm(alarmList.length > 0);
  }, [alarmList]);

  // 获取安装位置
  const getPosition = (deviceCode?: number) => {
    const point = points?.find((a) => a?.deviceCode == deviceCode);
    if (!point) return "未绑定测点";
    return `${point?.station?.name}-${point?.facility?.name}-${point?.name}`;
  };
  return (
    <div className={classNames(className, "w-30 h-10 flex flex-row")}>
      <Switch
        className="p-0"
        size="large"
        label={["开启报警", "关闭报警"]}
        value={isAlarmSounding}
        onChange={(v) => {
          setIsAlarmSounding(v as boolean);
        }}
      />
      <Tooltip content={`温度报警：${alarmList.length}`}>
        <Button
          className="ml-10"
          variant="text"
          size="small"
          onClick={() => {
            setVisible(true);
          }}
          icon={
            <div>
              <Alarm
                theme="multi-color"
                className="relative top-0 left-0"
                size="24"
                fill={["red", "red", "#FFF", "#43CCF8"]}
                strokeLinejoin="miter"
                strokeLinecap="square"
              />
              {isAlarm && (
                <Alarm
                  className="absolute top-0 left-2 animate-ping"
                  theme="multi-color"
                  size="24"
                  fill={["#F45A39", "#F4350D", "#FFF", "#43CCF8"]}
                  strokeLinejoin="miter"
                  strokeLinecap="square"
                />
              )}
            </div>
          }
        />
      </Tooltip>
      <AlarmSounding isAlarm={isAlarm} isAlarmSounding={isAlarmSounding} />
      <Dialog
        mode="modeless"
        header={`设备报警信息:${alarmList?.length}`}
        draggable={true}
        visible={visible}
        footer={false}
        width={"70%"}
        onClose={() => {
          setVisible(false);
        }}
        onOpened={() => {
          console.log("dialog is open");
        }}
      >
        <List
          size="small"
          style={{ maxHeight: 500, overflow: "auto" }}
          stripe={true}
        >
          {alarmList?.map((_item, index) => {
            return (
              <ListItem
                key={index}
                action={
                  <Space>
                    <div className="w-40 text-red-600">
                      <span>温度值：{_item.value1}</span>
                    </div>
                    <span>
                      报警时间：{" "}
                      {dayjs(_item.time).format("YYYY-MM-DD HH:mm:ss")}
                    </span>
                  </Space>
                }
              >
                <ListItemMeta
                  title={
                    <div className="flex gap-5">
                      <span className="text-blue-500">
                        设备ID:{_item?.deviceCode}
                      </span>
                      <span>
                        安装位置：
                        {getPosition(_item.deviceCode)}
                      </span>
                    </div>
                  }
                />
              </ListItem>
            );
          })}
        </List>
      </Dialog>
    </div>
  );
};
export default AlarmTip;
